# coding:utf-8
import os
import time
import serial

from PIL import ImageFont
from apscheduler.schedulers.background import BackgroundScheduler

from devs import Camera, Screen, NetWatcher, Battery, Clock
from water_level import get_water_level


class WaterLevelWatcher(object):
    def __init__(self):
        # init screen
        self.screen = Screen(fps=20)
        welcome_handler = self.screen.add_animate("asset/welcome.gif", repeat=True)
        # 准备记录日志
        self.log_dir = "./log"
        if not os.path.exists(self.log_dir):
            os.mkdir(self.log_dir)
        self.log_list = []
        # 初始化各个模块
        self.cam = Camera()
        self.net_watcher = NetWatcher(self.screen)
        self.battery = Battery(self.screen)
        self.clock = Clock(self.screen)
        # 结束欢迎界面，开始刷新各个组件
        self.screen.del_obj(welcome_handler)
        self.battery.start_display()
        self.clock.start_display()
        self.net_watcher.start_display()
        # 准备文字显示部分变量
        self.text_handler = [None, None, None]  # 分别对应t-2,t-1, t
        self.text_fonts = [ImageFont.truetype("asset/MSYH.TTC", size=size) for size in [15, 15, 20]]  # 准备字体文件
        self.text_positions = [(70, 18), (70, 38), (2, 28)]
        self.upadte_water_level()
        self.scheduler = BackgroundScheduler()
        self.scheduler.add_job(self.upadte_water_level, "interval", seconds=10, id="update_water_level")
        self.scheduler.start()

    def upadte_water_level(self):
        if self.net_watcher.command_queue.empty():
            return
        else:
            command = self.net_watcher.command_queue.get()
            if command != b'\x80\x04\x00\x66\x00\x01\xcf\xc4':
                return
        # 开始测量，删掉旧的文字，播放测量动画
        if self.text_handler[2] is not None:
            self.screen.del_obj(self.text_handler[2])
        loading_handler = self.screen.add_animate("asset/load.gif", pos=(20, 28))
        try:
            # 多次测量,并去掉测量失败的
            water_level_list = [get_water_level(self.cam.get_frame()) for i in range(3)]
            water_level_list = [item for item in water_level_list if item > 0]
            # 取均值否则测量失败
            water_level = sum(water_level_list) / len(water_level_list) if len(water_level_list) > 0 else -1
        except Exception:
            water_level = -1
        # 记入相应的log列表
        self.net_watcher.response_queue.put(water_level)
        self.log_list.append((time.strftime("%Y/%m/%d-%H:%M:%s"), water_level))
        self.screen.del_obj(loading_handler)
        # 告知用户测量结果是否成功
        loading_handler = self.screen.add_animate("asset/loadsuccess.gif" if water_level > 0 else "asset/loadfail.gif"
                                                  , pos=(18, 28), repeat=False)
        time.sleep(0.5)
        self.screen.del_obj(loading_handler)
        # 找出需要显示的部分
        log_to_show = (3 - len(self.log_list[-3:])) * ["未测量"] + \
                      ["{:.2f}".format(log_value[1]) if log_value[1] > 0 else "失败" for log_value in self.log_list[-3:]]
        for i in range(3):
            if self.text_handler[i] is not None:
                self.screen.del_obj(self.text_handler[i])
            self.text_handler[i] = self.screen.add_text(log_to_show[i], pos=self.text_positions[i],
                                                        font=self.text_fonts[i])


if __name__ == '__main__':
    watcher = WaterLevelWatcher()
    while True:
        pass
    watcher.screen.stop()
